package com.superpai.utils;

import java.io.ByteArrayOutputStream;
import java.util.Comparator;
import java.util.TreeMap;

import android.os.Debug;
import android.util.Log;

import com.superpai.common.Constants;

/**
 * @author Devin.Hu
 * @date 2011-8-12
 * @version V1.0
 * @description 参数处理类
 */
public final class ParameterUtils {


	/** 参数map **/
	TreeMap<String, String> paramsMap = new TreeMap<String, String>(new Comparator<Object>() {
		public int compare(Object o1, Object o2) {
			if (o1 == null || o2 == null)
				return 0;
			else
				return String.valueOf(o1).compareTo(String.valueOf(o2));
		}
	});


	/**
	 * 添加参数
	 * 
	 * @param name
	 * @param value
	 * @return
	 */
	private void addParam(String name, String value) {
		
		if(StringUtils.isEmpty(name) || StringUtils.isEmpty(value) || "0".endsWith(value)){
			return;
		}
		
		if (!StringUtils.isEmpty(paramsMap.get(name))) {
			throw new IllegalArgumentException("该参数名{ "+name+" }不可重复添加.");
		}
		paramsMap.put(name, value);
	}

	/**
	 * 添加参数
	 * 
	 * @param name
	 * @param value
	 * @return
	 */
	public void addStringParam(String name, String value) {
		addParam(name, value);
	}

	/**
	 * 添加参数
	 * 
	 * @param name
	 * @param value
	 * @return
	 */
	public void addStringParam(String name, int value) {
		addParam(name, String.valueOf(value));
	}
	

	/**
	 * 
	 * @param cmdId
	 * @param signParams
	 * @param secretKey
	 * @param charset
	 * @return
	 * @throws Exception
	 */
	public void makeSign(String apiMethodName, TreeMap<String, String> signParams, String secretKey, String charset) throws Exception
	{
		ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
		byteStream.write(apiMethodName.getBytes(charset));
		
		for (String key : signParams.keySet()) 
		{
			//System.out.println("key = " + key + " value = " + signParams.get(key));
			byteStream.write(key.getBytes(charset));
			byteStream.write(signParams.get(key).getBytes(charset));
		}
		byteStream.write(secretKey.getBytes(charset));
		byte[] array = byteStream.toByteArray();
		
		
		String sign = Md5Util.makeMd5Sum(array);
		if(Debug.isDebuggerConnected()){
			Log.i("makeSign success : ", sign);
		}
		
		addStringParam(Constants.SYS_PARAM_SIGN, sign);
	}


	public TreeMap<String, String> getParamsMap() {
		return paramsMap;
	}

	public void setParamsMap(TreeMap<String, String> paramsMap) {
		this.paramsMap = paramsMap;
	}
}
